package com.zhucai.credit.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.google.common.io.Files;

/**
 * @author taojie
 *
 */
public class FileUtils {
	
	
	private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
	
	private static Map<String,String> reqProp;
	
	static {
		reqProp = Maps.newHashMap();
		reqProp.put("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
	}
	
	public static void appendLine(String file,String content) {
		try {
			// 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
			FileWriter writer = new FileWriter(file, true);
			writer.write(content+"\r\n");
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	
	public static File saveFileFromURL(String url,final String saveas){	
		if(url==null || saveas.endsWith("null")) {
			return null;
		}
		url = url.replaceAll(" ", "%20");
		for(int i=1;i<=10;i++) {
			File f = new File(saveas);
			if(i > 1 || (f.exists() && f.length() == 0 )) {
				System.out.println("重试 删除");
				f.delete();
			} 
			try {
				Files.createParentDirs(f);
				if(f.createNewFile()) {
					
					HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
					for(Entry<String,String> e : reqProp.entrySet()) {
						connection.setRequestProperty(e.getKey(),e.getValue()); 
					}
					
					connection.setConnectTimeout(1000 * 15);
					connection.setReadTimeout(1000 * 55);

					if(connection.getResponseCode() == 404) {
						return null;
					}
					InputStream in = connection.getInputStream();
					Files.write(IOUtils.toByteArray(in), f);

				}
				return f;
			} catch (FileNotFoundException e) {
				f.deleteOnExit();
				logger.error(e.getMessage());
				logger.error("找不到文件: "+url );
				return null;
			} catch (UnknownHostException e) {
				logger.warn("===========================");
				logger.warn("网络闪断，休息片刻");
				logger.warn("===========================");
				try {
					Thread.sleep(1000 * 5);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (IOException e) {
				logger.error(url);
				logger.error("网络错误: "+e.getMessage() );
				logger.error("第"+i+"次 ，重试！");
			}
		}
		return null;

	}
	
	
	public static InputStream getInputStreamFromURL(String url) {
		//Logger logger = Logger.getLogger(PartsCrawlService.class);
		URL u = null;
		try {
			u = new URL(url);
		} catch (MalformedURLException e) {
			logger.error(e.getMessage()+" : "+url);
			return null;
		}
		
		for(int retry = 1;retry <= 5;retry++) {
			try {
				URLConnection connection = u.openConnection();
				for(Entry<String,String> e : reqProp.entrySet()) {
					connection.setRequestProperty(e.getKey(),e.getValue()); 
				}
				connection.setConnectTimeout(1000 * 30);
				connection.setReadTimeout(1000 * 60);
				InputStream in = connection.getInputStream();
				return in;
			} catch (IOException e) {
				logger.warn("第"+retry+"次 : "+url);
			}
		}
		return null;

	}
	
	
	public static void main(String[] args) throws Exception{
		URL url = new URL("https://lc-mediaplayerns-live-s.legocdn.com/public/v0a/v58/0a589cd6-fba9-486a-8c59-020fad55e01c_2d742c94-e482-4b8d-b650-a6de00f5993a_en-us_6_256.mp4");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("HEAD");
		//conn.connect();
		System.out.println(conn.getResponseCode());
	}
}
